#!/usr/bin/env python

"""Replace CRLFs with LFs at end of lines. Also expand tabs.
 Print names of changed files."""

import os
import sys
import string
import getopt

def main():

    tabsize = 8
    quiet = 0
    try:
        opts, args = getopt.getopt(sys.argv[1:], '-qt:')
        if not args:
            raise getopt.error, "At least one file argument required"
    except getopt.error, msg:
        print msg
        print "usage:", sys.argv[0], "[-q] [-t n] files ..."
        return

    for optname, optvalue in opts:
        if optname == '-q':
            quiet = 1
        if optname == '-t':
            tabsize = int(optvalue)

    for file in args:
        process(file, quiet, tabsize)

def process(file, quiet, tabsize):
    try:
        text = open(file).read()
    except IOError, msg:
        print "%s: I/O error: %s" % (`file`, str(msg))
        return
    newtext = string.replace(text, '\r\n','\n')
    newtext = string.expandtabs(newtext, tabsize)
    if newtext == text:
        return

    # write the backup file
    if not quiet:
        backup = file + "~"
        try:
            os.unlink(backup)
        except os.error:
            pass
        
        try:
            os.rename(file, backup)
        except os.error:
            pass
        
    open(file, "w").write(newtext)

    if not quiet:
        print file

if __name__ == '__main__':
    main()
